<template>
  <div>
    <el-dialog
      :before-close="handleClose"
      :title="status === 'Add' ? '新增套装' : '编辑套装'"
      :visible.sync="dialogVisible"
      width="1000px"
    >
      <div>
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
          label-width="100px"
        >
          <el-form-item label="套装名称" prop="suit_name">
            <el-input
              v-model="ruleForm.suit_name"
              placeholder="请输入套装名称"
              style="width: 80%;"
            ></el-input>
          </el-form-item>
          <el-form-item label="套装介绍" prop="suit_desc">
            <el-input
              v-model="ruleForm.suit_desc"
              :rows="3"
              placeholder="请输入套装介绍"
              style="width: 80%;"
              type="textarea"
            ></el-input>
          </el-form-item>

          <el-form-item label="套装图片" prop="picture">
            <el-upload

              :http-request="customizeUpload"
              :on-success="handleSuccess"
              :show-file-list="false"
              action=""
              class="avatar-uploader"
            >
              <img
                v-if="ruleForm.picture"
                :src="ruleForm.picture"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="套装包含单品" prop="productChecked">
            <el-select
              v-model="ruleForm.productChecked"
              clearable
              filterable
              multiple
              placeholder="请选择单品"
              style="width:415px"
              @change="handleChangeProduct"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.product_id"
                :label="item.product_name"
                :value="item.product_id"
              ></el-option>
            </el-select>
            <div class="text-red-500 leading-none mt-2">请选择6个单品</div>
          </el-form-item>

          <el-form-item label="套装风格" prop="checkedCities">
            <el-select
              v-model="ruleForm.checkedCities"
              clearable
              multiple
              placeholder="请选择套装风格"
              style="width:415px"
            >
              <el-option
                v-for="item in styleLabelOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="天数&价格">
            <div
              v-for="(item, index) in days_price_arr"
              :key="'天价' + index"
              :class="[index ? 'mt-2' : '']"
            >
              <el-select
                v-model="item.day"
                class="mr-3"
                @change="handleChooseDay(item.day)"
              >
                <el-option
                  v-for="(item, index) in daysOptions"
                  :key="'天数' + index"
                  :label="item.label"
                  :value="item.value"
                >
                  <span slot="suffix">天</span>
                </el-option>
              </el-select>
              <el-input
                v-model="item.original_price"
                class="mr-3"
                style="width:200px"
              >
                <span slot="suffix">原价</span>
              </el-input>
              <el-input v-model="item.price" class="mr-3" style="width:200px">
                <span slot="suffix">套装价</span>
              </el-input>
              <el-button v-if="index" @click.prevent="removePrice(item)"
              >删除
              </el-button
              >
            </div>
          </el-form-item>
          <el-form-item>
            <div class="text-red-500 leading-none mb-2">
              暂时仅可选择7天/15天/30天
            </div>
            <el-button @click="addPrice">新增</el-button>
          </el-form-item>
          <el-form-item label="出售状态" prop="sale_status">
            <el-radio-group v-model="ruleForm.sale_status">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>

          <!--          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>-->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          :loading="submitLoading"
          type="primary"
          @click="submitForm('ruleForm')"
        >提交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDetailData, postData, postEditData } from '@/api/personalizedMall/suit'

export default {
  name: 'addEditModal',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 模态框的状态 Add 为新增  Edit为编辑
    status: {
      type: String,
      default: ['Add']
    },
    // 选择类别选择项
    productOptions: {
      type: Array,
      default: () => []
    },
    // 风格标签选择项
    styleLabelOptions: {
      type: Array,
      default: () => []
    },
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dataTime: {
        startTime: null,
        endTime: null
      },
      daysOptions: [
        { value: 7, label: '7天' },
        { value: 15, label: '15天' },
        { value: 30, label: '30天' }
      ],
      submitLoading: false,
      ruleForm: {
        suit_name: null, // 商品名称
        suit_desc: null, // 商品介绍
        picture: null, // 图片url
        style_ids: null, // 风格标签id，多个用英文逗号连接，必须
        days_price: null, // 天数与价格
        product_ids: null,
        sale_status: 1, // 出售状态：1：上架；0：下架，必须
        checkedCities: [],
        productChecked: []
      },
      days_price_arr: [
        { price: undefined, original_price: undefined, day: undefined }
      ],
      cateArr: [24, 23],
      inputArr: [4, 33, 26],

      rules: {
        suit_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        suit_desc: [
          { required: true, message: '请输入商品介绍', trigger: 'blur' }
        ],
        picture: [
          { required: true, message: '请上传展示图片', trigger: 'blur' }
        ],
        // special: [
        //   { required: true, message: "请上传/输入效果", trigger: "blur" }
        // ],
        show_type: [
          { required: true, message: '请输入选择展示位置', trigger: 'blur' }
        ],
        /*style_ids: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],*/
        sale_status: [
          { required: true, message: '请选择出售状态', trigger: 'blur' }
        ],
        checkedCities: [
          { required: true, message: '请选择展示风格', trigger: 'blur' }
        ],
        productChecked: [
          {
            type: 'array',
            required: true,
            message: '请选择套装单品',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    handleClose(done) {
      this.$emit('update:dialogVisible', false)
      for (const detailKey in this.ruleForm) {
        this.ruleForm[detailKey] = detailKey === 'checkedCities' ? [] : null
      }
      this.$emit('update:status', 'Add')

      this.resetForm('ruleForm')
    },
    submitForm(formName) {
      let data = {}
      for (let key in this.ruleForm) {
        if (key !== 'checkedCities' && key !== 'productChecked') {
          data[key] = this.ruleForm[key]
        }
      }
      if (this.ruleForm.checkedCities) {
        data['style_ids'] = this.ruleForm.checkedCities.join(',')
      }
      if (this.ruleForm.productChecked) {
        data['product_ids'] = this.ruleForm.productChecked.join(',')
      }
      let day_price = []
      this.days_price_arr.forEach(item => {
        day_price.push(`${item.day}:${item.price}`)
      })
      data.days_price = day_price.join(';')

      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.submitLoading = true
          let detail
          // 新增活动商品
          if (this.status === 'Add') {
            detail = await postData(data)
          } else {
            // 编辑
            let data1 = { id: this.id, ...data }
            detail = await postEditData(data1)
          }
          if (detail.code === 200) {
            this.$message.success(
              this.status === 'Add' ? '添加成功!' : '编辑成功'
            )
            this.$emit('update:dialogVisible', false)
            this.$emit('updateTable')
            for (const detailKey in this.ruleForm) {
              this.ruleForm[detailKey] =
                detailKey === 'checkedCities' ? [] : null
            }
            this.$emit('update:status', 'Add')
          }
          this.submitLoading = false
        } else {
          this.submitLoading = false

          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.ruleForm = {
        suit_name: null, // 商品名称
        suit_desc: null, // 商品介绍
        picture: null, // 图片url
        style_ids: null, // 风格标签id，多个用英文逗号连接，必须
        days_price: null, // 天数与价格
        product_ids: null,
        sale_status: 1, // 出售状态：1：上架；0：下架，必须
        checkedCities: [],
        productChecked: []
      }
      this.days_price_arr = [
        { price: undefined, original_price: undefined, day: undefined }
      ]
    },

    handleChangeProduct(val) {
      if (val.length > 6) {
        this.ruleForm.productChecked.pop()
      }
    },

    handleChooseDay(day) {
      let product_arr = []
      this.productOptions.forEach(item => {
        this.ruleForm.productChecked.forEach(i => {
          if (item.product_id === i) {
            product_arr.push(item)
          }
        })
      })

      let pre_total_price = 0
      product_arr.forEach(item => {
        item.product_price.forEach(i => {
          pre_total_price += i.day === day ? i.price : 0
        })
      })
      this.days_price_arr.forEach(item => {
        item.original_price =
          item.day === day
            ? pre_total_price
            : item.original_price
              ? item.original_price
              : undefined
      })
    },

    handleSuccess() {
      this.ruleForm.picture = this.ossLastImgUrl
    },

    addPrice() {
      this.days_price_arr.push({
        day: undefined,
        original_price: undefined,
        price: undefined
      })
    },

    removePrice(item) {
      let index = this.days_price_arr.indexOf(item)
      if (index !== -1) {
        this.days_price_arr.splice(index, 1)
      }
    }
  },
  watch: {
    async status(newVal) {
      /* 当 status 为 Edit 则 为编辑框, 需要完成数据的回显   */
      if (newVal === 'Edit') {
        const detail = await getDetailData(this.id)
        if (detail.code === 200) {
          this.ruleForm.suit_name = detail.data.suit_name
          this.ruleForm.suit_desc = detail.data.suit_desc
          this.ruleForm.picture = detail.data.picture
          this.days_price_arr = detail.data.suit_price_info
          this.ruleForm.sale_status = detail.data.on_sale === 2 ? 0 : 1
          this.ruleForm.checkedCities = detail.data.suit_style_ids
          this.ruleForm.productChecked = detail.data.suit_product_info.map(
            item => {
              return item.id
            }
          )
        }
      }
    }
  }
}
</script>

<style scoped>
::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}
</style>
